import {useEffect} from 'react';
import {
  Switch,
  Route,
  useRouteMatch,
  useHistory,
} from 'react-router-dom';
import Home from './pages/Home';
import Login from './pages/Login';
import store from './store';
import config from 'config';

const paths = config.paths;

type Match = ReturnType<typeof useRouteMatch>;

type ROUTE_CONFIG_FACTORY = (match: Match) => {
  path: string,
  component: any,
}[]

const route_config_factory: ROUTE_CONFIG_FACTORY = (_: Match) => [
  {
    path: paths.ART_GALLARY,
    component: () => <div>Art Gallery</div>,
  },
  {
    path: paths.MUSIC_HALL,
    component: () => <div>Music Hall</div>,
  },
  {
    path: paths.STORE,
    component: () => <div>Store</div>,
  },
  {
    path: paths.QA,
    component: () => <div>Q&A</div>,
  },
  {
    path: paths.LOGIN,
    component: <Login />,
  },
  {
    path: paths.HOME,
    component: <Home />,
  },
]

export default () => {
  const match = useRouteMatch();
  const history = useHistory();

  useEffect(() => {
    if (!store.isLogin()) {
      history.push('/login')
    }
  }, [history])

  return (
      <Switch>
        {route_config_factory(match).map(({path, component}) => (
          <Route path={path} key={path}>
            {component}
          </Route>
        ))}
      </Switch>
  );
}
